/**
 * 封装uni-app的网络请求
 */

// 基础请求URL，根据实际情况修改
const BASE_URL = 'https://api.example.com';

// 请求拦截器
const beforeRequest = (config) => {
  // 添加token等通用请求头
  const token = uni.getStorageSync('token');
  if (token) {
    config.header = {
      ...config.header,
      'Authorization': `Bearer ${token}`
    };
  }
  return config;
};

// 响应拦截器
const handleResponse = (res) => {
  // 这里可以处理通用的响应逻辑，如401鉴权失败等
  if (res.statusCode === 401) {
    // 清除token
    uni.removeStorageSync('token');
    // 跳转登录页
    uni.navigateTo({
      url: '/pages/index/index'
    });
    return Promise.reject(new Error('未授权，请重新登录'));
  }
  
  return res.data;
};

// 请求错误处理
const handleError = (error) => {
  uni.showToast({
    title: error.message || '网络错误，请稍后重试',
    icon: 'none'
  });
  return Promise.reject(error);
};

// 封装请求方法
const request = (options) => {
  const config = beforeRequest(options);
  
  return new Promise((resolve, reject) => {
    uni.request({
      url: options.baseUrl ? options.baseUrl + options.url : BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: options.header || {},
      timeout: options.timeout || 60000,
      success: (res) => {
        resolve(handleResponse(res));
      },
      fail: (err) => {
        reject(handleError(err));
      }
    });
  });
};

// 封装常用请求方法
const http = {
  get: (url, data = {}, options = {}) => {
    return request({
      url,
      method: 'GET',
      data,
      ...options
    });
  },
  post: (url, data = {}, options = {}) => {
    return request({
      url,
      method: 'POST',
      data,
      ...options
    });
  },
  put: (url, data = {}, options = {}) => {
    return request({
      url,
      method: 'PUT',
      data,
      ...options
    });
  },
  delete: (url, data = {}, options = {}) => {
    return request({
      url,
      method: 'DELETE',
      data,
      ...options
    });
  }
};

export default http; 